<template>
  <n-button
    @click="addNewField()"
    type="primary"
    dashed
    >添加新领域</n-button
  >
  <n-tree
    block-line
    draggable
    :data="data"
    :node-props="nodeProps"
    @drop="handleDrop"
    :default-expanded-keys="fieldTree.defaultExpandedKeys"
    :on-update:expanded-keys="updatePrefixWithExpaned"
  />
  <n-dropdown
    placement="bottom-start"
    trigger="manual"
    :x="xRef"
    :y="yRef"
    :options="options"
    :show="showDropdownRef"
    :on-clickoutside="onClickoutside"
    @select="handleSelect"
  />
  <FieldEditDrawer v-model="editSettings"></FieldEditDrawer>
  <FieldTreeDelModal v-model="editSettings"></FieldTreeDelModal>
</template>

<script lang="ts" setup>
import FieldEditDrawer from "./fieldTreeBtn/FieldEditDrawer.vue";
import FieldTreeDelModal from "./fieldTreeBtn/FieldTreeDelModal.vue";
import { FieldContentData, FieldIdData } from "@model/fieldTree";
import type { SurfaceSetting } from "@model/surfaceSetting";
import UseFieldTree from "@pinias/UseFieldTree";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import pinia from "@pinias/pinia";
import { AlertCircleOutline } from "@vicons/ionicons5";
import { useMessage } from "naive-ui";
import { NIcon, NTree, TreeDropInfo, TreeOption, NButton } from "naive-ui";
import { h, ref, watch, reactive } from "vue";

//全局数据
const { getFieldTree } = UseFieldTree(pinia);
const fieldTree = getFieldTree();
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting: SurfaceSetting = getSurfaceSetting();

// 页面数据
const editSettings = reactive<{ toEdit: boolean; toDelete: boolean; toDealRowId: number | undefined }>({
  toEdit: false,
  toDelete: false,
  toDealRowId: undefined,
});

// 树形数据获取
const getTreeData = (arg: Array<FieldIdData>) => {
  const result: Array<any> = [];
  for (var i = 0; i < arg.length; i++) {
    const id = arg[i].id;
    const oldData = fieldTree.getFieldDataById(id);
    const children1 = getTreeData(arg[i].children);
    if (oldData !== undefined) {
      result.push({
        key: oldData.id,
        label: oldData.topic,
        children: children1,
        // prefix: () =>
        //   h(NIcon, null, {
        //     default: () => h(PlanetOutline),
        //   }),
        suffix: () => {
          if (FieldContentData.checkIsGoing(oldData))
            return h(NIcon, null, {
              default: () => h(AlertCircleOutline),
            });
        },
        // actions:
      });
    }
  }
  return result;
};
const data = ref(getTreeData(fieldTree.fieldTree));
watch(fieldTree.fieldData, () => {
  // console.log('fieldPanel.fieldTree',fieldTree);
  data.value = getTreeData(fieldTree.fieldTree);
  //console.log('data.value',data);
});

// 拖拽
const getOrignalData = (arg: Array<any>) => {
  const result: Array<any> = [];
  for (var i = 0; i < arg.length; i++) {
    const id = arg[i].key;
    const children1 = getOrignalData(arg[i].children);
    result.push({ id: id, children: children1 });
  }
  return result;
};
function findSiblingsAndIndex(node: TreeOption, nodes?: TreeOption[]): [TreeOption[], number] | [null, null] {
  if (!nodes) return [null, null];
  for (let i = 0; i < nodes.length; ++i) {
    const siblingNode = nodes[i];
    if (siblingNode.key === node.key) return [nodes, i];
    const [siblings, index] = findSiblingsAndIndex(node, siblingNode.children);
    if (siblings && index !== null) return [siblings, index];
  }
  return [null, null];
}
const handleDrop = ({ node, dragNode, dropPosition }: TreeDropInfo) => {
  const [dragNodeSiblings, dragNodeIndex] = findSiblingsAndIndex(dragNode, data.value);
  // console.log('dragNodeSiblings',dragNodeSiblings,dragNodeIndex);
  if (dragNodeSiblings === null || dragNodeIndex === null) return;
  dragNodeSiblings.splice(dragNodeIndex, 1);
  if (dropPosition === "inside") {
    // console.log("inside");
    if (node.children) {
      node.children.unshift(dragNode);
    } else {
      node.children = [dragNode];
    }
  } else if (dropPosition === "before") {
    const [nodeSiblings, nodeIndex] = findSiblingsAndIndex(node, data.value);
    if (nodeSiblings === null || nodeIndex === null) return;
    nodeSiblings.splice(nodeIndex, 0, dragNode);
  } else if (dropPosition === "after") {
    const [nodeSiblings, nodeIndex] = findSiblingsAndIndex(node, data.value);
    if (nodeSiblings === null || nodeIndex === null) return;
    nodeSiblings.splice(nodeIndex + 1, 0, dragNode);
  }
  data.value = Array.from(data.value);
  const original = getOrignalData(data.value);
  fieldTree.setFieldIdDataList(original);
  //console.log("handleDrop",fieldTree)
};

// 右键菜单
const message = useMessage();
const options = [
  {
    label: "编辑",
    key: "edit",
  },
  {
    label: () => h("span", { style: { color: "red" } }, "删除"),
    key: "delete",
  },
];
const showDropdownRef = ref(false);
const xRef = ref(0);
const yRef = ref(0);
const onClickoutside = () => {
  showDropdownRef.value = false;
};
let deleteIdHasChild = false;
const handleSelect = (key: string, node: string) => {
  console.log(key, node);
  showDropdownRef.value = false;
  if (key == "edit") {
    editSettings.toEdit = true;
  }
  if (key == "delete") {
    if (deleteIdHasChild) message.error("存在子领域不可删除");
    else editSettings.toDelete = true;
  }
};
const addNewField = () => {
  editSettings.toDealRowId = undefined;
  editSettings.toEdit = true;
};

// 点击
const nodeProps = ({ option }: { option: TreeOption }) => {
  // @contextmenu.prevent.stop="click2FieldSetting"
  //   @click="click2Field"
  return {
    // 左击
    onClick() {
      // onClick(e)
      if (!option.children && !option.disabled) {
        // message.info('[Click] ' + option.label)
        console.log("onClick");
      }
    },
    // 双击
    ondblclick() {
      if (option.key !== undefined) {
        //console.log("click2Field", option);
        surfaceSetting.showField.pop();
        surfaceSetting.showField.push(parseInt(option.key.toString()));
        surfaceSetting.GoalListKey = new Date().getTime();
      }
    },
    // 右击
    onContextmenu(e: MouseEvent) {
      //取消默认的浏览器自带右键
      e.preventDefault();
      if (option.children !== undefined && option.key !== undefined) {
        editSettings.toDealRowId = parseInt(option.key.toString());
        showDropdownRef.value = true;
        xRef.value = e.clientX;
        yRef.value = e.clientY;
        deleteIdHasChild = option.children?.length > 0;
      }
    },
  };
};

// 展开效果
const updatePrefixWithExpaned = (
  keys: Array<string | number>,
  option: Array<TreeOption | null>,
  meta: {
    node: TreeOption | null;
    action: "expand" | "collapse" | "filter";
  },
) => {
  fieldTree.setDefaultExpandedKeys(keys);
  if (!meta.node) return;
  switch (meta.action) {
    case "expand":
      // meta.node.prefix = () =>
      //   h(NIcon, null, {
      //     default: () => h(SunnyOutline),
      //   });
      break;
    case "collapse":
      // meta.node.prefix = () =>
      //   h(NIcon, null, {
      //     default: () => h(PlanetOutline),
      //   });
      break;
  }
};
</script>
